using Microsoft.Extensions.Logging;
using AgentFrameworkDemo.Models;
using AgentFrameworkDemo.Services;

namespace AgentFrameworkDemo;

/// <summary>
/// 诗词演示程序 - 展示Microsoft风格Agent工具的简洁性
/// </summary>
public class PoetryDemo
{
    private readonly ILogger<PoetryDemo> _logger;
    private readonly IAgentManager _agentManager;

    public PoetryDemo(ILogger<PoetryDemo> logger, IAgentManager agentManager)
    {
        _logger = logger;
        _agentManager = agentManager;
    }

    /// <summary>
    /// 演示诗词创作和分析 - 使用Microsoft风格API
    /// </summary>
    public async Task DemonstratePoetryAnalysis()
    {
        Console.WriteLine("📜 诗词演示 - Microsoft风格Agent工具");
        Console.WriteLine("=====================================");

        try
        {
            // 1. 创建诗词专家Agent
            var poetryAgentDefinition = new AgentDefinition
            {
                Name = "诗词专家",
                Description = "精通中国古典诗词的AI专家，擅长诗词创作、分析和解读",
                Tags = ["tool", "poetry", "literature", "chinese"],
                Capabilities = new AgentCapabilities
                {
                    EnableMemory = true,
                    EnableTools = false
                },
                Configuration = new AgentConfiguration
                {
                    Model = new AIModelConfig
                    {
                        Provider = "ZhipuAI",
                        ModelId = "glm-4.5",
                        ApiKey = "08ffd1f87b0e4914be6542b892d327cd.QKnNO0dKRUljxxXv",
                        Endpoint = "https://open.bigmodel.cn/api/paas/v4/chat/completions",
                        Temperature = 0.8,
                        MaxTokens = 500
                    }
                },
                CustomSystemPrompt = @"你是{{AgentName}}，一位精通中国古典诗词的文学专家。

你的专长包括：
- 诗词创作和仿写
- 诗词意境分析
- 诗词格律讲解
- 诗词背景解读
- 诗词情感表达分析

请用优美典雅的语言回答问题，展现深厚的文学修养。在分析诗词时，请注重：
1. 意境的描绘和感受
2. 情感的表达和传递
3. 艺术手法的运用
4. 文化内涵的解读

{{Description}}"
            };

            Console.WriteLine("\n🎯 创建诗词专家Agent...");
            var poetryAgent = await _agentManager.CreateAgentAsync(poetryAgentDefinition);
            Console.WriteLine($"✅ 诗词专家创建成功: {poetryAgent.Id}");

            // 2. Microsoft风格：转换为AI函数（1行代码）
            Console.WriteLine("\n🔄 Microsoft风格转换 - agent.AsAIFunction()");
            var poetryFunction = poetryAgent.AsAIFunction("poetry_expert", "诗词分析专家");
            Console.WriteLine($"✅ 转换成功: {poetryFunction.Name}");

            // 3. 执行经典诗词分析（1行代码）
            Console.WriteLine("\n📝 分析经典诗词：'问君能有几多愁'");
            var result = await poetryFunction.InvokeAsync("请分析李煜的词句'问君能有几多愁，恰似一江春水向东流'的意境和情感表达");

            // 4. 展示结果
            Console.WriteLine("\n🎨 诗词分析结果:");
            if (result is Dictionary<string, object> dict)
            {
                var content = dict.GetValueOrDefault("content")?.ToString() ?? "无内容";
                var executionTime = dict.GetValueOrDefault("execution_time")?.ToString();
                var success = dict.GetValueOrDefault("success")?.ToString();

                Console.WriteLine($"✅ 执行状态: {success}");
                Console.WriteLine($"⏱️  执行时间: {executionTime}");
                Console.WriteLine($"📖 分析内容:");
                Console.WriteLine("----------------------------------------");
                Console.WriteLine(content);
                Console.WriteLine("----------------------------------------");

                // 显示企业级特性
                if (dict.TryGetValue("enterprise", out var enterpriseInfo) &&
                    enterpriseInfo is Dictionary<string, object> enterprise)
                {
                    Console.WriteLine("\n🏢 企业级特性:");
                    Console.WriteLine($"📊 审计ID: {enterprise.GetValueOrDefault("audit_log_id")}");
                    if (enterprise.TryGetValue("performance_metrics", out var perf) &&
                        perf is Dictionary<string, object> performance)
                    {
                        Console.WriteLine($"⚡ 性能指标: {performance.GetValueOrDefault("total_execution_time_ms")}ms");
                    }
                }
            }

            // 5. 展示API简洁性
            Console.WriteLine("\n📊 API简洁性对比:");
            Console.WriteLine("❌ 旧方式（复杂）:");
            Console.WriteLine("   await agentToolExecutor.RefreshAgentToolsAsync();");
            Console.WriteLine("   var tools = await agentToolExecutor.GetAvailableToolsAsync();");
            Console.WriteLine("   var request = new ToolExecutionRequest { /* 复杂配置 */ };");
            Console.WriteLine("   var result = await agentToolExecutor.ExecuteToolAsync(request);");

            Console.WriteLine("\n✅ 新方式（Microsoft风格）:");
            Console.WriteLine("   var func = agent.AsAIFunction(\"poetry_expert\");");
            Console.WriteLine("   var result = await func.InvokeAsync(\"分析请求\");");
            Console.WriteLine("   // 总共2行代码！");

            // 6. 额外演示：续写诗句
            Console.WriteLine("\n✍️  续写诗句演示:");
            var continuationResult = await poetryFunction.InvokeAsync("请续写'问君能有几多愁'的下一句，保持相同的意境和格律");

            if (continuationResult is Dictionary<string, object> contDict &&
                contDict.TryGetValue("content", out var contContent))
            {
                Console.WriteLine($"🌟 续写结果: {contContent}");
            }

            Console.WriteLine("\n🎉 诗词演示完成！");
            Console.WriteLine("Microsoft风格Agent工具：简洁、优雅、强大");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "诗词演示失败");
            Console.WriteLine($"\n❌ 演示失败: {ex.Message}");
        }
    }
}